const router = require('@koa/router')()
  , { User, Note, Data, Skillbag } = require('../schema')
  , Util = require('../../util/index.js')
  , crypto = require('../../middleware/crypto/index')
const jwt = require('../../middleware/jwt/jwt')

router.get('/alitoken', async ctx => {
  crypto(function (data) {
    return ctx.body = {
      data: data.tokenData,
      msg: "获取token成功",
      code: 0
    }
  })
})


router.put('/userinfo', async ctx => {
  const { nickName, sex, job, label, birthday, address, name, introduce, avatar, tags, skill } = ctx.request.body;
  const arr = [];
  const obj = {}
  if (birthday) {
    arr.push({ birthday: birthday, type: 'string', label: 'birthday' },)
    obj.birthday = birthday
  }
  if (nickName) {
    arr.push({ nickName: nickName, type: 'string', label: 'nickName' },)
    obj.nickName = nickName
  }
  if (sex) {
    arr.push({ sex: sex, type: 'number', label: 'sex' },)
    obj.sex = sex
  }
  if (job) {
    arr.push({ job: job, type: 'string', label: 'job' },)
    obj.job = job
  }
  if (label) {
    arr.push({ label: label, type: 'string', label: 'label' },)
    obj.label = label
  }
  if (address) {
    arr.push({ address: address, type: 'string', label: 'address' },)
    obj.address = address
  }
  if (name) {
    arr.push({ name: name, type: 'string', label: 'name' },)
    obj.name = name
  }
  if (introduce) {
    arr.push({ introduce: introduce, type: 'string', label: 'introduce' },)
    obj.introduce = introduce
  }
  if (avatar) {
    arr.push({ avatar: avatar, type: 'string', label: 'avatar' },)
    obj.avatar = avatar
  }
  if (tags) {
    arr.push({ tags: tags, type: 'object', label: 'tags' },)
    obj.tags = tags
  }
  if (skill) {
    arr.push({ skill: skill, type: 'object', label: 'skill' },)
    obj.skill = skill
  }


  const verFlog = Util.checkUndefined(arr);
  if (verFlog) {
    const authorization = ctx.request.header.authorization;
    const token = authorization.split(' ')[1]
    const result = await jwt.verify(token.split('.')[0])

    return ctx.body = await User.updateOne({ _id: result.split('.')[1] }, obj).then(async () => {
      const data = await User.findOne({ _id: result.split('.')[1] })
      const userData = Object.assign({}, data._doc)
      delete userData.password
      return {
        data: userData,
        code: 0,
        msg: '修改成功'
      }
    })
  } else {
    ctx.body = Util.back(-101)
  }
})

router.put('/userdata', async ctx => {
  const { account, qd } = ctx.request.body;
  const verFlog = Util.checkUndefined([
    { qd: qd, type: 'number', label: 'qd' },
    { account: account, type: 'string', label: 'account' },
  ]);
  if (verFlog) {
    const oldData = await Data.findOne({ account })
    // console.log(Util.formatTime(oldData.updated), Util.formatTime(new Date(Date.now())));
    if (qd === 0) {
      const updatedTime = Util.formatTime(oldData.updated).split(' ')[0]
      const newDateTime = Util.formatTime(new Date(Date.now())).split(' ')[0]
      const createdTime = Util.formatTime(oldData.created).split(' ')[0]
      const qd = oldData.qd
      if (updatedTime === newDateTime) {
        if (createdTime === newDateTime && !qd) {
          return ctx.body = {
            data: false,
            code: 0,
            msg: '今日未签到'
          }
        } else {
          return ctx.body = {
            data: true,
            code: 0,
            msg: '今日已签到'
          }
        }
      } else {
        return ctx.body = {
          data: true,
          code: 0,
          msg: '今日已签到'
        }
      }
    } else {
      const newQd = oldData.qd + 1
      oldData.qd = newQd
      return ctx.body = await Data.updateOne({ account }, { qd: newQd }).then(res => {
        return {
          data: oldData,
          code: 0,
          msg: '修改成功'
        }
      })
    }
  } else {
    ctx.body = Util.back(-101)
  }
})



router.get('/skillbag', async ctx => {
  const authorization = ctx.request.header.authorization;
  const token = authorization.split(' ')[1]
  const _id = token.split('.')[1]
  const flog = await Skillbag.findOne({ _id })
  if (flog) {
    return ctx.body = {
      data: flog,
      code: 0,
      msg: '查询成功'
    }
  } else {
    await new Skillbag({ _id, classBag: [] }).save()
    return ctx.body = {
      data: [],
      code: 0,
      msg: '查询成功'
    }
  }
})


router.put('/skillbag', async ctx => {
  const authorization = ctx.request.header.authorization;
  const token = authorization.split(' ')[1]
  const _id = token.split('.')[1]
  const classBag = ctx.request.body.classBag
  return ctx.body = await Skillbag.updateOne({ _id }, { classBag: classBag }).then(async res => {
    const oldData = await Skillbag.findOne({ _id })
    return {
      data: oldData,
      code: 0,
      msg: '添加成功'
    }
  })

})










// router.get('/userdata/qd', async ctx => {
//   const { account } = ctx.query
//   const verFlog = Util.checkUndefined([
//     { account: account, type: 'string', label: 'account' }
//   ]);

//   if(verFlog) {
//     const oldData = await Data.findOne({account})
//     if(oldData.updated === ) {
//       return ctx.body = {
//         data: true,
//         code: 0,
//         msg: '今日已签到'
//       }
//     } else {

//     }
//   } else {
//     ctx.body = Util.back(-101)
//   }

// })














































router.get('/userinfo', async ctx => {
  const authorization = ctx.request.header.authorization;
  const userId = await Util.getTokenId(authorization)
  return ctx.body = await User.findOne({ _id: userId }).then(res => {
    console.log(res)
    // delete userData.password
    return {
      data: res,
      code: 0,
      msg: '查询成功'
    }
  })
})


router.get('/getToken', async ctx => {
  util.handler(function (obj) {
    ctx.body = {
      code: 0,
      data: obj,
      msg: "返回数据成功！"
    }
  })
})


router.put('/user', async ctx => {
  const { user, nickName, sex, job, ps } = ctx.request.body;
  const arr = [];
  if (user) arr.push({ user: user, type: 'string', label: 'user' },)
  if (nickName) arr.push({ nickName: nickName, type: 'string', label: 'nickName' },)
  if (sex) arr.push({ sex: sex, type: 'string', label: 'sex' },)
  if (job) arr.push({ job: job, type: 'string', label: 'job' },)
  if (ps) arr.push({ ps: ps, type: 'string', label: 'ps' },)
  const verFlog = util.checkUndefined(arr);

  if (verFlog) {
    const updateData = () => {
      const obj = {}
      if (nickName) obj.nickName = nickName
      if (sex) obj.sex = sex
      if (job) obj.job = job
      if (ps) obj.ps = ps
      return obj
    }
    ctx.body = await User.updateOne({ user }, updateData()).then(res => {
      return {
        code: 0,
        data: null,
        msg: '修改成功'
      }
    })
  } else {
    ctx.body = util.back(-101)
  }
})

router.post('/note', async ctx => {
  const { user, title, content } = ctx.request.body;

  const verFlog = util.checkUndefined([
    {
      user: user,
      type: 'string',
      label: 'user'
    },
    {
      title: title,
      type: 'string',
      label: 'title'
    },
    {
      content: content,
      type: 'string',
      label: 'content'
    },
  ]);

  if (verFlog) {
    if (await User.findOne({ user })) {
      ctx.body = await new Note({ user, title, content }).save().then(res => {
        return {
          code: 0,
          msg: '新建成功',
          data: null
        }
      }).catch(err => {
        return util.back(500)
      })
    } else {
      ctx.body = util.back(-402)
    }
  } else {
    ctx.body = util.back(-101)
  }
})

router.get('/note', async ctx => {
  const { page, size, user, title, state } = ctx.query
  const verFlog = util.checkUndefined([
    {
      user: user,
      type: 'string',
      label: 'user'
    },
    {
      page: page,
      type: 'string',
      label: 'page'
    },
    {
      size: size,
      type: 'string',
      label: 'size'
    }
  ]);

  if (verFlog) {
    if (await User.findOne({ user })) {
      const limit = parseInt(size)
      const skip = limit * parseInt(page)
      let findObj = { user }
      if (title) {
        const regexp = new RegExp(title, 'i')
        findObj.$or = [{ title: { $regex: regexp } }]
      }
      ctx.body = await Note.find(findObj).limit(skip).skip(skip - limit).then(async res => {
        let length = await Note.find({ user }).count()
        return {
          code: 0,
          msg: '查询成功',
          data: res,
          total: length
        }
      }).catch(err => {
        return util.back(500)
      })
    } else {
      ctx.body = util.back(-402)
    }
  } else {
    ctx.body = util.back(-101)
  }
})


router.put('/note', async ctx => {
  const { id, title, content, state } = ctx.request.body;

  let checkArr = []
  let findObj = {}

  if (state) {
    findObj = { state }
    checkArr = [
      {
        id: id,
        type: 'string',
        label: 'id'
      },
      {
        state: state,
        type: 'number',
        label: 'state'
      }
    ]
  } else {
    findObj = { title, content }
    checkArr = [
      {
        id: id,
        type: 'string',
        label: 'id'
      },
      {
        title: title,
        type: 'string',
        label: 'title'
      },
      {
        content: content,
        type: 'string',
        label: 'content'
      },
    ]
  }

  const verFlog = util.checkUndefined(checkArr);

  if (verFlog) {
    ctx.body = await Note.updateOne({ _id: id }, findObj).then(res => {
      return {
        code: 0,
        msg: '修改成功',
        data: res
      }
    }).catch(err => {
      return util.back(500)
    })
  } else {
    ctx.body = util.back(-101)
  }
})


module.exports = router.routes()